import Taro, { navigateTo } from "@tarojs/taro";
import axios from "axios";
import { store } from "@/store";

axios.interceptors.request.use(
  (config: any) => {
    console.log("request config", config);
    return config;
  },
  (error) => {
    // eslint-disable-next-line no-console
    console.error("[Axios Request Error]: ", error);
  }
);

axios.interceptors.response.use(
  (res: any) => {
    console.error("[Axios Response Error`]: ", res);

    return Promise.resolve(res);
  },
  (error) => {
    console.error("[Axios Response Error]: ", error);
    if (error?.response?.data) {
      error = error?.response?.data;
    }
    return Promise.reject(error);
  }
);

function createFetchHandler() {
  return function (options: any): Promise<any> {
    const {
      user: { auth },
    } = store.getState();
    const defaultConfig = {
      baseURL: options["url"].startsWith("http")
        ? ""
        : options.prefix || process.env.SERVER_HOST,
      withCredentials: false,
      headers: auth.token
        ? {
            Authorization: JSON.stringify({
              token: auth.token,
            }),
          }
        : {},
      timeout: 60000,
      url: options["url"],
    };

    const { headers, ...rest } = options;

    const cfg = { ...defaultConfig, ...rest };

    cfg.headers = {
      ...cfg.headers,
      ...headers,
    };
    console.log("request cfg", cfg);

    return axios.request(cfg).then(({ data: res }) => {
      console.log("request res", res);
      if (
        typeof res === "string" ||
        res.code === "0" ||
        res.status ||
        res.success
      ) {
        return res;
      } else if (res?.code === "A0230") {
        Taro.showToast({
          title: res.msg || "登录状态失效，请重新登录",
          icon: "none",
          duration: 2000,
        });
        setTimeout(() => {
          navigateTo({
            url: "/sub_common/pages/auth/index",
          });
        }, 2000);
      } else {
        return Promise.reject(res);
      }
    });
  };
}

export const request = createFetchHandler();

export default createFetchHandler;
